<template>
  <div style="display: flex;flex-direction: column;align-items: center;width: 100%;">
    <div style="margin-top: 18px;margin-left: 18px;align-self: flex-start;cursor: pointer;" @click="goBack()">
      <i class="el-icon-back">返回</i>
    </div>
    <el-card style="width: 80%;margin-top: 20px">
      <el-divider content-position="left">基本信息</el-divider>
      <div style="width: 100%;display: flex;align-items: center;flex-direction: column">
        <el-form :model="userData" ref="userData" label-width="32%" style="width: 90%;margin-top: 40px"
                 label-position="left">
          <template>
            <el-form-item align="right" v-show="!disable">
              <el-button :disabled="disable" type="primary" @click="saveData">保存</el-button>
            </el-form-item>
            <el-form-item align="right" v-show="disable">
              <el-button :disabled="!disable" type="info" v-show="user.roleId !== 3" @click="disable=!disable">修改</el-button>
            </el-form-item>
          </template>
          <el-row>
            <el-col :span="24">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="学号" prop="stuNo">
                    <el-input :disabled="disable" v-model="userData.stuNo" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="userData.name" :disabled="disable" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="性别" prop="sex">
                    <el-radio :disabled="disable" label="男" v-model="userData.sex"></el-radio>
                    <el-radio :disabled="disable" label="女" v-model="userData.sex"></el-radio>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="学院" prop="college">
                    <el-input :disabled="disable" v-model="userData.college" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="专业" prop="major">
                    <el-input :disabled="disable" v-model="userData.major" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="班级" prop="grade">
                    <el-input :disabled="disable" v-model="userData.grade" autocomplete="off"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="出生" prop="birth">
                    <el-date-picker v-model="userData.birth" :disabled="disable" style="width: 100%;"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="实际年龄" prop="realAge">
                    <el-input type="number" v-model="userData.realAge" :disabled="disable"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="过敏史" prop="nativePlace">
                    <el-input v-model="userData.historyCheck" :disabled="disable"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="民族" prop="nation">
                    <el-input v-model="userData.nation" :disabled="disable"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="籍贯" prop="nativePlace">
                    <el-input v-model="userData.nativePlace" :disabled="disable"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="绑定微信" prop="nativePlace">
                    <el-popover
                        v-if="!userData.openId"
                        placement="bottom"
                        width="500"
                        @after-enter="bindWeChat(userData.id)"
                        trigger="click">
                      先关注
                      <img src="./wxgz.png" width="200px">
                      后扫码
                      <vue-qr :logoSrc="imageUrl" :text="qrCodeImgUrl" :size="200"></vue-qr>
                      <el-button slot="reference" v-show="user.roleId !== 3">绑定微信</el-button>
                    </el-popover>
                    <el-button @click="testSend()" v-show="user.roleId !== 3">测试</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-divider content-position="left">信息分析</el-divider>
      <el-row style="text-align: center">
        身高-体重-BMI统计图
        <div style="width: 100%;height: 300px" id="line"></div>
      </el-row>
      <el-row style="text-align: center">
        运动统计
        <div style="width: 100%;height: 300px" id="barLine"></div>
      </el-row>
      <el-divider content-position="left">饮食推荐</el-divider>
      <el-row style="text-align: center">
        <el-descriptions class="margin-top" :column="2" border>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-date"></i>
              时间
            </template>
            {{ this.lastTime }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template slot="label">
              <i class="el-icon-document"></i>
              建议摄入量
            </template>
            {{ this.bmrValue }}
          </el-descriptions-item>
          <el-descriptions-item label="饮食建议" :span="2">
            <el-input type="textarea" v-model="suggestion" :autosize="true" :readonly="true"></el-input>
          </el-descriptions-item>
          <el-descriptions-item label="早餐" :span="2">
            <el-input type="textarea" v-model="breakfast" :autosize="true"
                      :readonly="foodFlag"></el-input>
          </el-descriptions-item>
          <el-descriptions-item label="中餐" :span="2">
            <el-input type="textarea" v-model="lunch" :autosize="true"
                      :readonly="foodFlag"></el-input>
          </el-descriptions-item>
          <el-descriptions-item label="午餐">
            <el-input type="textarea" v-model="dinner" :autosize="true"
                      :readonly="foodFlag"></el-input>
          </el-descriptions-item>
        </el-descriptions>
        <el-button type="primary" @click="foodFlag = !foodFlag" v-show="foodFlag && user.roleId !== 3">修改</el-button>
        <el-button type="primary" @click="saveFoods()" v-show="!foodFlag">保存</el-button>
        <el-button type="primary" @click="foodFlag = !foodFlag" v-show="!foodFlag">取消</el-button>

      </el-row>
      <el-row style="text-align: center;margin-top: 20px" v-show="!foodFlag">
        能量预计摄入：{{ this.expectPower }} 千卡
        <div style="height: 100px;border:1px solid #000;margin-bottom: 20px">
          <el-tag
              v-for="food in calculateFoods"
              :key="food.name"
              closable
              :type="food.type"
              @close="handleCloseTag(food)">
            {{ food.name }}
          </el-tag>
        </div>

        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="食物名称">
            <el-input v-model="formInline.name" placeholder="输入食物名称"></el-input>
          </el-form-item>
          <el-form-item label="食物分类">
            <el-select v-model="formInline.category" placeholder="选择食物分类" clearable>
              <el-option label="主食类" value="1"></el-option>
              <el-option label="肉蛋类" value="2"></el-option>
              <el-option label="大豆及制品类" value="3"></el-option>
              <el-option label="蔬菜菌藻类" value="4"></el-option>
              <el-option label="水果类" value="5"></el-option>
              <el-option label="奶类及奶制品类" value="6"></el-option>
              <el-option label="油脂类" value="7"></el-option>
              <el-option label="坚果类" value="8"></el-option>
              <el-option label="调味品类" value="9"></el-option>
              <el-option label="饮料类" value="10"></el-option>
              <el-option label="零食及冷饮类" value="11"></el-option>
              <el-option label="其他" value="12"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
            <el-button type="primary" id="btn" @click="copyFood">一键复制以上食物</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row style="text-align: center;" v-show="!foodFlag">
        <el-col :offset=6 :span="12">
          <el-table
              :data="tableData"
              style="width: 100%;margin-bottom: 20px">
            <el-table-column
                prop="name"
                label="名称"
                :formatter="nameFormatter"
                width="180">
            </el-table-column>
            <el-table-column
                prop="healthLevel"
                label="推荐"
                :formatter="recommendationFormatter"
                align="center">
            </el-table-column>
            <el-table-column
                prop="calory"
                label="热量(千卡/100ml/100g)"
                width="180">
            </el-table-column>

            <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="230">
              <template slot-scope="scope">
                <el-button
                    @click.native.prevent="countNumberFn(scope.$index, tableData)"
                    size="small">
                  加入计算
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import Message from '../../components/messages/index'
import Clipboard from 'clipboard'
import vueQr from 'vue-qr'

export default {
  name: "index",
  components: {vueQr},
  data() {
    return {
      qrCodeImgUrl: "",
      imageUrl: require("./wx.png"),
      expectPower: 0,
      calculateFoods: [],
      userData: {},
      disable: true,
      heightData: 180,
      weightData: 120,
      suggestion: "",
      label: [],
      height: [],
      weight: [],
      bmiValue: [],
      yundongTime: [],
      reLiang: [],
      user: JSON.parse(localStorage.getItem("user")),
      checkData: {},
      bmrValue: "",
      breakfast: "",
      lunch: "",
      dinner: "",
      lastTime: "",
      currentId: 0,
      foodFlag: true,
      formInline: {
        name: "",
        category: ""
      },
      tableData: []
    }
  },
  methods: {
    testSend(){
      this.$http.get("/user/testSend").then((res) => {
        if(res.status === 200){
          Message.success("发送成功");
        }
      })
    },
    bindWeChat(id) {
      this.$http.get("/weChat/qrAuthorize?userId=" + id).then((res) => {
        console.log(res);
        this.qrCodeImgUrl = res.data
      })
    },
    copyFood() {
      let textStr = "";
      this.calculateFoods.forEach((item) => {
        textStr = textStr + item.name + "\n";
      })
      let clipboard = new Clipboard("#btn", {
        text() {
          //返回字符串
          return textStr;
        },
      });
      // 复制成功
      clipboard.on("success", (e) => {
        console.log(e, '复制成功');
        clipboard.destroy();
      });
      // //复制失败
      clipboard.on("error", (e) => {
        console.log(e, '复制失败');
        clipboard.destroy();
      });
    },
    handleCloseTag(data) {
      console.log(data)
      this.expectPower -= data.calory;
      this.calculateFoods.splice(this.calculateFoods.indexOf(data), 1);
    },
    countNumberFn(index, data) {
      const types = ["", "success", "info", "warning", "danger"]
      const row = data[index];
      this.expectPower += row.calory;
      this.calculateFoods.push({
        name: row.name + "(" + row.calory + "千卡)",
        type: types[index % 4],
        calory: row.calory
      })
    },
    nameFormatter(row) {
      return row.name + "（" + row.calory + "千卡）";
    },
    recommendationFormatter(row) {
      switch (row.healthLevel) {
        case 1 :
          return "推荐";
        case 2 :
          return "适量";
        case 3 :
          return "少吃";
        default:
          return "";
      }
    },
    onSubmit() {
      this.$http.get("/food/list", {
        params: {
          "name": this.formInline.name,
          "category": this.formInline.category
        }
      }).then((res) => {
        if (res.status === 200) {
          this.tableData = res.data;
        }
      })
    },
    saveFoods() {
      let data = {}
      data.id = this.currentId;
      data.breakfast = this.breakfast;
      data.lunch = this.lunch;
      data.dinner = this.dinner;
      this.$http.post("/checkInfo/update", data).then(res => {
        if (res.status === 200) {
          Message.success("保存成功")
          this.foodFlag = !this.foodFlag
        }
      })
    },
    goBack() {
      window.history.back()
    },
    initData() {
      this.$http.get("/user/get/" + this.user.id).then(res => {
        if (res.status === 200) {
          this.userData = res.data
        }
      })
    },
    saveData() {
      this.$http.post("/user/update", this.userData).then(res => {
        if (res.status === 200) {
          Message.success("操作成功");
          localStorage.setItem("user", JSON.stringify(this.userData));
          this.disable = !this.disable;
          this.initData();
        }
      })
    },
    getOptions() {
      let Line = echarts.init(document.getElementById("line"));
      let BarLine = echarts.init(document.getElementById("barLine"));
      let lineOption = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          },
          formatter: function (c) {
            let height = {};
            let weight = {};
            let bmi = {};
            c.forEach((item, index) => {
              switch (index) {
                case 0:
                  height.name = item.name
                  height.format = 'm';
                  height.value = item.value
                  height.seriesName = item.seriesName
                  height.marker = item.marker
                  break;
                case 1:
                  weight.format = 'kg';
                  weight.value = item.value
                  weight.seriesName = item.seriesName
                  weight.marker = item.marker
                  break;
                case 2:
                  bmi.value = item.value
                  bmi.seriesName = item.seriesName
                  bmi.marker = item.marker
                  break;
                default:
                  break;
              }
            })
            return height.name + `<br/>`
                + weight.marker + weight.seriesName + `: ` + weight.value + weight.format + `<br />`
                + bmi.marker + bmi.seriesName + `: ` + bmi.value + `<br />`
                + height.marker + height.seriesName + `: ` + height.value + height.format
          }
        },
        legend: {
          color: ["#F58080", "#47D8BE", "#F9A589"],
          data: ['身高', '体重', 'BMI'],
          left: 'center',
          bottom: 'bottom',
          y: 'top'
        },
        grid: {
          top: 'middle',
          left: '3%',
          right: '4%',
          bottom: '3%',
          height: '80%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.label,
          axisLine: {
            lineStyle: {
              color: "#312f2f"
            }
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#DDD'
            }
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: "#333"
            },
          },
          nameTextStyle: {
            color: "#999"
          },
          splitArea: {
            show: false
          }
        },
        series: [{
          name: '身高',
          type: 'line',
          data: this.height,
          color: "#F58080",
          lineStyle: {
            normal: {
              width: 5,
              color: {
                type: 'linear',

                colorStops: [{
                  offset: 0,
                  color: '#FFCAD4' // 0% 处的颜色
                }, {
                  offset: 0.4,
                  color: '#F58080' // 100% 处的颜色
                }, {
                  offset: 1,
                  color: '#F58080' // 100% 处的颜色
                }],
                globalCoord: false // 缺省为 false
              },
              shadowColor: 'rgba(245,128,128, 0.5)',
              shadowBlur: 10,
              shadowOffsetY: 7
            }
          },
          itemStyle: {
            normal: {
              color: '#F58080',
              borderWidth: 10,
              borderColor: "#F58080"
            }
          },
          smooth: true
        },
          {
            name: '体重',
            type: 'line',
            data: this.weight,
            lineStyle: {
              normal: {
                width: 5,
                color: {
                  type: 'linear',

                  colorStops: [{
                    offset: 0,
                    color: '#AAF487' // 0% 处的颜色
                  },
                    {
                      offset: 0.4,
                      color: '#47D8BE' // 100% 处的颜色
                    }, {
                      offset: 1,
                      color: '#47D8BE' // 100% 处的颜色
                    }
                  ],
                  globalCoord: false // 缺省为 false
                },
                shadowColor: 'rgba(71,216,190, 0.5)',
                shadowBlur: 10,
                shadowOffsetY: 7
              }
            },
            itemStyle: {
              normal: {
                color: '#AAF487',
                borderWidth: 10,
                /*shadowColor: 'rgba(72,216,191, 0.3)',
                 shadowBlur: 100,*/
                borderColor: "#AAF487"
              }
            },
            smooth: true
          },
          {
            name: 'BMI',
            type: 'line',
            data: this.bmiValue,
            lineStyle: {
              normal: {
                width: 5,
                color: {
                  type: 'linear',

                  colorStops: [{
                    offset: 0,
                    color: '#F6D06F' // 0% 处的颜色
                  },
                    {
                      offset: 0.4,
                      color: '#F9A589' // 100% 处的颜色
                    }, {
                      offset: 1,
                      color: '#F9A589' // 100% 处的颜色
                    }
                  ],
                  globalCoord: false // 缺省为 false
                },
                shadowColor: 'rgba(249,165,137, 0.5)',
                shadowBlur: 10,
                shadowOffsetY: 7
              }
            },
            itemStyle: {
              normal: {
                color: '#F6D06F',
                borderWidth: 10,
                /*shadowColor: 'rgba(72,216,191, 0.3)',
                 shadowBlur: 100,*/
                borderColor: "#F6D06F"
              }
            },
            smooth: true
          }
        ]
      };
      let barLineOption = {
        backgroundColor: '#ffffff',
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(1, 13, 19, 0.5)',
          borderWidth: 0,
          padding: 2,
          textStyle: {
            color: '#fff',
            fontSize: 15,
          },
          axisPointer: {
            type: 'shadow'
          },
        },
        grid: {
          top: '10%',
          bottom: '10%',
          left: '5%',
          right: '5%',
          containLabel: true,
        },
        legend: {
          data: ['运动时长', '能量消耗'],
          left: '350',
          top: '10',
          textStyle: {
            padding: [4, 0, 0, 0],
            color: '#33FFFF',
          },
          itemWidth: 15,
          itemHeight: 10,
          itemGap: 10,
        },
        xAxis: {
          type: 'category',
          data: this.label,
          axisLine: {
            lineStyle: {
              color: 'rgba(66, 192, 255, .3)',
            },
          },
          axisLabel: {
            //x轴文字倾斜设置
            rotate: 0,
            textStyle: {
              color: 'rgba(19,103,219,0.81)',
            },
          },
        },

        yAxis: [
          {
            name: '(分钟)',
            type: 'value',
            splitLine: {
              show: false,
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: '#000000',
              },
            },
          },
          {
            name: '（千卡）',
            type: 'value',
            scale: true,
            position: 'right',
            splitLine: {
              show: false,
            },
            axisLabel: {
              show: true,
              textStyle: {
                fontSize: 12,
                color: '#000000',
              },
            },
          },
        ],
        series: [
          {
            name: '运动时长',
            type: 'bar',
            barWidth: '13px',
            itemStyle: {
              normal: {
                color: '#4bdfff',
                barBorderRadius: 8,
              },
            },
            data: this.yundongTime,
          },
          {
            name: '能量消耗',
            type: 'line',
            yAxisIndex: 1, //使用的 y 轴的 index，在单个图表实例中存在多个 y轴的时候有用
            smooth: false, //平滑曲线显示
            symbol: 'circle', //标记的图形为实心圆
            symbolSize: 9, //标记的大小
            itemStyle: {
              normal: {
                color: '#ff8020',
                borderColor: '#fff', //圆点透明 边框
                borderWidth: 2,
              },
            },
            lineStyle: {
              color: '#ffa43a',
            },
            data: this.reLiang,
          },
        ],

      };
      Line.setOption(lineOption);
      BarLine.setOption(barLineOption);
    },
    getDataAnalysis() {
      let user = this.user;
      let checkData = this.checkData;
      this.heightData = checkData.height;
      this.weightData = checkData.weight;
      this.$http.get("/checkInfo/getDataAnalysis/" + user.id).then(res => {
        if (res.status === 200) {
          this.label = res.data.label;
          this.height = res.data.height;
          this.weight = res.data.weight;
          this.bmiValue = res.data.bmiValue;
          this.yundongTime = res.data.yundongTime;
          this.reLiang = res.data.reLiang;
          this.suggestion = res.data.suggestion;
          this.lastTime = res.data.lastTime;
          this.bmrValue = res.data.bmrValue + "（千卡）";
          this.breakfast = res.data.breakfast;
          this.lunch = res.data.lunch;
          this.dinner = res.data.dinner;
          this.currentId = res.data.id;
          this.getOptions();
        }
      }).catch(() => Message.error("访问出错!"))
    },
    getChecked() {
      this.$http.get("/checkInfo/getCurrentCheckInfo/" + this.user.id).then(res => {
        if (res.status === 200) {
          // console.log("个人检查数据=====",res.data)
          this.checkData = res.data;
          this.getDataAnalysis();
        }
      });
    }
  },
  mounted() {
    this.initData();
    this.getChecked();
  },
  created() {

  }
}
</script>

<style scoped>
/deep/ .el-textarea__inner {
  color: red
}

.qrcode {
  display: inline-block;
  width: 132px;
  height: 132px;
  background-color: #fff;
  padding: 6px;
  box-sizing: border-box;
}
</style>
